package com.ali.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * 自定义服务端处理器
 */
public class MyServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 通道读取
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) {
        if (httpObject instanceof HttpRequest httpRequest) {
            System.out.println("客户端地址：" + channelHandlerContext.channel().remoteAddress());
            System.out.println("请求URI：" + httpRequest.uri());
            //请求图标不做返回
            if ("/favicon.ico".equals(httpRequest.uri())) {
                return;
            }

            //构建缓冲区
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello 客户端", StandardCharsets.UTF_8);
            //构建HttpResponse
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            //设置返回类型
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            //设置返回长度
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            //写入返回内容
            channelHandlerContext.write(defaultFullHttpResponse);
            //刷新
            channelHandlerContext.flush();
        }
    }
}
